uploadURL = "/proj"
users = []
projName = ""
actingUser = document.getElementById('theUser').innerHTML.split(',')[1].substring(4)

var alt = false

var webs = new WebSocket('ws://' + location.hostname + ":" + location.port)

function sendCodeSave() {

	var xmlhttp = new XMLHttpRequest();
	code = arrayBubble[workingBubble].bubble.getArea().getValue()
	xmlhttp.open("POST", location.href + "proj/save/?code=" + code, true)
	xmlhttp.onload = function() {
		if(xmlhttp.readyState == 4) {
		}
	}

	xmlhttp.send(null)

}

function sendCodeCoop(id) {
	var pathNameBubbleToChange = arrayBubble[id].bubblePath
	var mainIndexFile = 0;
	for( i = 0; i < arrayBubble.length; i++) {
		if(arrayBubble[i].bubblePath == pathNameBubbleToChange) {
			mainIndexFile = i;
			break;
		}
	}

	var bubbleToChange = id - mainIndexFile;

	var message = {
		type : "coop",
		bubbleToChange : bubbleToChange,
		absolutePath : pathNameBubbleToChange,
		newCode : arrayBubble[workingBubble].bubble.getArea().getValue()
	};
	webs.send(JSON.stringify(message));
}

function keyBinding(event) {

	if(event.keyCode == 18)
		alt = true
	if(alt && event.keyCode == 83) {
		sendCode()
		alt = false
	}
}

function getCode(id, view, callback) {
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("GET", location.href + "proj/file/?path=" + id, true)
	xmlhttp.onload = function() {
		if(xmlhttp.readyState == 4) {

			var text = JSON.parse(xmlhttp.response)
			//console.log(text)
			parseTheTree(text.fileName, text.code, text.path)
			if(callback) {
				callback(view)
			}
		}
	}

	xmlhttp.send(null)

}

function addUser() {
	var user = document.getElementById('inputuser')
	var userlist = document.getElementById('userlist')
	var currentUsers = getAllUsers()
	if(user.value != "" && currentUsers.indexOf(user.value) != -1) {
		userlist.innerHTML += '<li>' + user.value + '</li>'
		users.push(user.value)
	}
	user.value = ""
	//console.log(users)
}

function closeUploadForm() {
	document.getElementById('uploadDiv').style.display = 'none'
	document.getElementById('userlist').innerHTML = ""
}

function setupForm() {
	var owner = document.getElementById('theUser').innerHTML.split(',')[1].substring(4)
	owner = owner.substring(0, owner.length - 1)
	//console.log(owner)
	users.push(owner)
	projName = document.getElementById('projname').value
	//console.log(projName)
	//console.log(users)
	uploadURL = '/proj/?name=' + projName + '&users='
	var userquery = ""
	for(i in users) {
		userquery += users[i] + '+'
	}
	uploadURL += userquery
	uploadURL = uploadURL.substring(0, uploadURL.length - 1)
	document.getElementById('form').setAttribute('action', uploadURL)
	console.log(document.getElementById('form').action)
}

function openFs() {
	var isOpen = document.getElementById("fs").style.left == '1214px'
	if(!isOpen) {
		$(document.getElementById("fs")).animate({
			left : 1214
		}, 200, function() {
			$(document.getElementById('theUser')).animate({
				opacity : 1
			}, 300)
			$(document.getElementById('filelist')).animate({
				opacity : 1
			}, 300)
			$(document.getElementById('groupcolors')).animate({
				opacity : 1
			}, 300)
		})
	} else {
		$(document.getElementById('groupcolors')).animate({
			opacity : 0
		}, 300)
		$(document.getElementById('theUser')).animate({
			opacity : 0
		}, 200)
		$(document.getElementById('filelist')).animate({
			opacity : 0
		}, 200, function() {
			$(document.getElementById("fs")).animate({
				left : 1430
			}, 200)
		})
	}
}

function openChat() {
	var isOpen = document.getElementById("chat").style.top == '598px'
	if(!isOpen) {
		$(document.getElementById("chat")).animate({
			top : 598
		}, 200, function() {
			$(document.getElementById('send')).animate({
				opacity : 1
			}, 200)
			$(document.getElementById('chatcontent')).animate({
				opacity : 1
			}, 200)
			$(document.getElementById('word')).animate({
				opacity : 1
			}, 200)
			$(document.getElementById('usronline')).animate({
				opacity : 1
			}, 300)
		})
	} else {
		$(document.getElementById('send')).animate({
			opacity : 0
		}, 200)
		$(document.getElementById('word')).animate({
			opacity : 0
		}, 200)
		$(document.getElementById('usronline')).animate({
			opacity : 0
		}, 200)
		$(document.getElementById('chatcontent')).animate({
			opacity : 0
		}, 200, function() {
			$(document.getElementById("chat")).animate({
				top : 793
			}, 200)
		})
	}
}

function lookUp(event) {
	if(event.keyCode == 13) {
		t = document.getElementById('word');
		n = document.getElementById('name');
		var message = {
			type : "chat",
			text : t.value,
			sender : document.getElementById("theUser").innerHTML.split(",")[1].split("!")[0].slice(4)
		};
		webs.send(JSON.stringify(message), function() {
			console.log("callback")
		});
	}
}

//behaviour on open
webs.onopen = function() {
	webs.send(JSON.stringify({
		type : "usrOnline",
		usr : document.getElementById("theUser").innerHTML.split(",")[1].split("!")[0].slice(4)
	}))
}
//behave like this when the WebSocket receives a message
webs.onmessage = function(message) {
	var x = JSON.parse(message.data);
	l = document.getElementById('result');

	try {
		var message = JSON.parse(x.message)
	} catch(e) {
		var message = x.message;
	}
	if(x.type == "chat") {
		l.innerHTML = l.innerHTML + "<li id='chatline'>" + message.sender + ": <div contenteditable='true'  onkeydown='edited(this)' id='" + message.id + "' style='font-size:13px; display:inline'>" + message.text + "</div></li><br>";
		document.getElementById('word').value = ""
		if(document.getElementById('chat').style.top == '793px') {
			document.getElementById('newmessage').style.opacity = 1
			$(newmessage).animate({
				opacity : 0
			}, 2000)
		}
	} else if(x.type == "coop") {

		var message = JSON.parse(x.message)
		var bubbleIndex = 0;
		var newCode = message.newCode;
		console.log(x.type)
		for( i = 0; i < arrayBubble.length; i++) {
			if(arrayBubble[i].bubblePath == message.absolutePath) {
				bubbleIndex = i + message.bubbleToChange;
				if(arrayBubble[bubbleIndex].bubble.getArea().getValue() != newCode) {
					arrayBubble[bubbleIndex].bubble.getArea().setValue(newCode)
					arrayBubble[bubbleIndex].bubble.getArea().refresh()
				}

				break;
			}

		}

	} else if(x.type == "usrOnline") {

		//	if(message.length > 1) {
		document.getElementById("usronline").innerHTML = ""
		for(i in message) {
			console.log(message[i])
			if(message[i] != document.getElementById("theUser").innerHTML.split(",")[1].split("!")[0].slice(4))
				document.getElementById("usronline").innerHTML += '<font color=#66FF33>&bull;</font>' + message[i] + "</br>"
		}
		// } else {
		// if(message[0] != undefined && message[0] != document.getElementById("theUser").innerHTML.split(",")[1].split("!")[0].slice(4))
		// document.getElementById("usronline").innerHTML += '<font color=#66FF33>&bull;</font>' + message[0] + "</br>"
		// else
		// document.getElementById("usronline").innerHTML == ""
		// }

	}

}
function edited(element) {
	//debugger;
	if(event.keyCode == 13) {
		t = element.innerHTML
		n = document.getElementById('name');
		i = element.attributes["id"]
		var message = {};
		message.id = i.value;
		message.text = t;
		message.sender = n.value;
		webs.send(JSON.stringify(message));
	}
}

function changeColorBlue() {
	var groupColorated = [];

	var actualGroup = arrayBubble[workingBubble].bubble.getGroupNumber();

	for( i = 0; i < arrayBubble.length; i++) {

		if(arrayBubble[i].bubble.getGroupNumber() == actualGroup && document.getElementById("container" + i)) {
			document.getElementById("container" + i).style.backgroundColor = 'rgba(63,63,252, 0.5)';
			document.getElementById('minibubbleNumber' + i).style.backgroundColor = 'rgba(63,63,252, 0.5)';
		}

	}
}

function changeColorPurple() {
	var groupColorated = [];

	var actualGroup = arrayBubble[workingBubble].bubble.getGroupNumber();

	for( i = 0; i < arrayBubble.length; i++) {

		if(arrayBubble[i].bubble.getGroupNumber() == actualGroup && document.getElementById("container" + i)) {
			document.getElementById("container" + i).style.backgroundColor = 'rgba(221,142,238, 0.5)';
			document.getElementById('minibubbleNumber' + i).style.backgroundColor = 'rgba(221,142,238, 0.5)';

		}

	}
}

function changeColorYellow() {
	var groupColorated = [];

	var actualGroup = arrayBubble[workingBubble].bubble.getGroupNumber();

	for( i = 0; i < arrayBubble.length; i++) {

		if(arrayBubble[i].bubble.getGroupNumber() == actualGroup && document.getElementById("container" + i)) {
			document.getElementById("container" + i).style.backgroundColor = 'rgba(189,196,78, 0.5)';
			document.getElementById('minibubbleNumber' + i).style.backgroundColor = 'rgba(189,196,78, 0.5)';

		}

	}
}

function changeColorGreen() {
	var groupColorated = [];

	var actualGroup = arrayBubble[workingBubble].bubble.getGroupNumber();

	for( i = 0; i < arrayBubble.length; i++) {

		if(arrayBubble[i].bubble.getGroupNumber() == actualGroup && document.getElementById("container" + i)) {
			document.getElementById("container" + i).style.backgroundColor = 'rgba(92,243,92, 0.5)'
			document.getElementById('minibubbleNumber' + i).style.backgroundColor = 'rgba(92,243,92, 0.5)'

		}

	}
}

function changeColorRed() {
	var groupColorated = [];

	var actualGroup = arrayBubble[workingBubble].bubble.getGroupNumber();

	for( i = 0; i < arrayBubble.length; i++) {

		if(arrayBubble[i].bubble.getGroupNumber() == actualGroup && document.getElementById("container" + i)) {
			document.getElementById("container" + i).style.backgroundColor = 'rgba(255,59,59, 0.5)'
			document.getElementById('minibubbleNumber' + i).style.backgroundColor = 'rgba(255,59,59, 0.5)'

		}

	}
}

function sendViewToServer() {
	console.log("sent")
	var viewJson = {}

	if(arrayBubble && arrayBubble.length > 0) {

		//var pathNameBubble = arrayBubble[0].bubblePath
		var counter = 0;
		var top, left;
		for( i = 0; i < arrayBubble.length; i++) {
			if(document.getElementById("container" + i) && document.getElementById("functionNumber" + i)) {
				top = arrayBubble[i].bubble.getContainer().style.top
				top = top.substring(0, top.length - 2)
				left = arrayBubble[i].bubble.getContainer().style.left
				left = parseInt(left.substring(0, left.length - 2)) - 9
				navLeft = document.getElementById("Navigator_index").style.left
				navLeft = parseInt(navLeft.substring(0, navLeft.length - 2)) * 15 - 9
				//console.log(left)
				//console.log(navLeft)
				left = left;
				pathNameBubble = arrayBubble[i].bubblePath

				viewJson[i] = {
					uniqueBubbleID : i,
					path : pathNameBubble,
					top : top,
					left : left,
					navLeft : navLeft,
					isOpen : arrayBubble[i].bubble.isOpen()

				}
			}
		}

		var toSend = JSON.stringify({
			user : document.getElementById("theUser").innerHTML.split(",")[1].split("!")[0].slice(4),
			view : viewJson
		});

		//console.log(toSend)

		var xmlhttp = new XMLHttpRequest();
		xmlhttp.open("POST", location.href + "proj/savesession/?session=" + toSend, true)
		xmlhttp.onload = function() {
			if(xmlhttp.readyState == 4) {
			}
		}
		xmlhttp.send(null)
	}
}

function createBubbleFromView(view) {
	//console.log(view)

	if(!document.getElementById("container" + view.uniqueBubbleID)) {

		arrayBubble[view.uniqueBubbleID].bubble.create(parseInt(view.uniqueBubbleID));

		//alert()
		//console.log(document.getElementById("container" + view.uniqueBubbleID))

	}
	var top = parseInt(view.top);
	var left = parseInt(view.left);
	var navLeft = parseInt(view.navLeft);

	document.getElementById("container" + view.uniqueBubbleID).style.top = top + "px";
	document.getElementById("container" + view.uniqueBubbleID).style.left = left + navLeft + "px";
	document.getElementById("minibubbleNumber" + view.uniqueBubbleID).style.top = top / 15 + 9 + "px";
	document.getElementById("minibubbleNumber" + view.uniqueBubbleID).style.left = ((left + navLeft) / 15 + 9) + "px";
	if(view.isOpen == true) {
		$(document.getElementById("functionNumber" + view.uniqueBubbleID)).trigger("dblclick");
	}
}

function askViewToServer() {

	console.log("asked")
	me = document.getElementById("theUser").innerHTML.split(",")[1].split("!")[0].slice(4)
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("GET", location.href + "session?user=" + me, true)
	xmlhttp.onload = function() {
		if(xmlhttp.readyState == 4) {
			if(xmlhttp.response == "No session")
				console.log("No session")
			else {
				var text = JSON.parse(xmlhttp.response)
				var viewArray = text.view
				console.log(viewArray)
				for(k in viewArray) {
					console.log(k)
					var view = viewArray[k]

					getCode(view.path, view, createBubbleFromView)
				}
			}

		}
	}
	xmlhttp.send(null)

}

window.onbeforeunload = function() {
//	sendViewToServer()

	localStorage.setItem('refreshCheck', "aaaaa")
}
function checkRefresh() {
	console.log(localStorage.getItem('refreshCheck'))
	if(localStorage.getItem('refreshCheck') == "0") {
		localStorage.setItem('refreshCheck', "1")
		console.log("first time")

	} else {

		console.log("second time")
	}

}